/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer.plugin;

import at.schauer.gregor.vienna.serializer.filter.AbstractFieldFilter;
import at.schauer.gregor.vienna.serializer.filter.FilterSupport;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @author Gregor Schauer
 */
public class FilterRemovePlugin<T> extends AbstractPhasePlugin<T> implements ReflectionUtils.FieldFilter {
	protected List<AbstractFieldFilter<?>> filters;

	public FilterRemovePlugin(List<AbstractFieldFilter<?>> filters, Phase... phases) {
		super(phases);
		this.filters = filters;
	}

	@Override
	protected <E extends T> Map<String, Object> process(Map<String, Object> map, Class<E> clazz) {
		doFilter(map, clazz, null);
		return map;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected <E extends T> E process(E obj, Map<String, Object> map) {
		doFilter(map, (Class<E>) obj.getClass(), obj);
		return obj;
	}

	public <E extends T> E doFilter(@Nonnull final Map<String, Object> map, @Nonnull Class<E> clazz, @Nullable E obj) {
		ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() {
			@Override
			public void doWith(Field field) throws IllegalAccessException {
				map.remove(field.getName());
			}
		}, this);
		return obj;
	}

	@Override
	public boolean matches(Field field) {
		return FilterSupport.matchesFilters(field, filters);
	}
}
